<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Base64 编码/解码工具</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-4">Base64 编码/解码工具</h1>
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-body">
                        <form id="base64Form">
                            <div class="mb-3">
                                <label for="inputText" class="form-label">输入文本</label>
                                <textarea class="form-control" id="inputText" rows="3" placeholder="请输入需要编码或解码的文本"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="operation" class="form-label">操作类型</label>
                                <select class="form-select" id="operation">
                                    <option value="encode">编码为 Base64</option>
                                    <option value="decode">解码 Base64</option>
                                </select>
                            </div>
                            <button type="button" class="btn btn-primary" onclick="processText()">执行</button>
                        </form>
                        <div class="mt-4">
                            <label for="resultText" class="form-label">结果</label>
                            <textarea class="form-control" id="resultText" rows="3" readonly></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS and Popper.js -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function processText() {
            const inputText = document.getElementById('inputText').value;
            const operation = document.getElementById('operation').value;
            let result;

            if (operation === 'encode') {
                result = btoa(inputText);
            } else {
                try {
                    result = atob(inputText);
                } catch (e) {
                    result = '解码失败：请输入有效的 Base64 编码文本！';
                }
            }

            document.getElementById('resultText').value = result;
        }
    </script>
</body>
</html>